<template>
  <div class="search-input">
    <div class="search-container">
      <div class="input-box" :style="{height: height +'px'}" :class="{'focus': focus}">
        <input :placeholder="placeholder" :autofocus="autofocus" @focus="focus = true" @blur="focus = false"
               v-model="modalValue" @keydown.enter="search"/>
      </div>
      <div class="search-right">
        <Icon v-if="modalValue" @click="onClose" class="close-icon" size="20" type="md-close"/>
        <div class="submit-box" :style="{width: submitWidth + 'px'}">
          <button class="submit-button" @click="search">搜索</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import {ref, watch} from "vue";

const props = defineProps({
  placeholder: String,
  value: String,
  autofocus: Boolean,
  height: {
    type: Number,
    default: 44
  },
  submitWidth: {
    type: Number,
    default: 120
  }
})

const emits = defineEmits(['search', 'update:value'])

const focus = ref(false)
const modalValue = ref('')

watch(() => props.value, (n) => {
  modalValue.value = n;
})

function onClose() {
  modalValue.value = '';
  emits('update:value', modalValue.value)
}

function search() {
  emits('search', modalValue.value)
  emits('update:value', modalValue.value)
}
</script>

<style lang="scss" scoped>
.search-input {
  .search-container {
    position: relative;

    .input-box {
      height: 44px;
      border: 2px solid rgba(0, 0, 0, .1);
      border-radius: 6px;
      padding-left: 16px;
      padding-right: 160px;
      transition: all .2s;
      background-color: rgba(255, 255, 255, .6);
      font-size: 18px;

      &:hover {
        border-color: rgba(0, 0, 0, .2);
      }

      &.focus {
        border-color: #2d8cf0;
      }

      input {
        width: 100%;
        height: 100%;
        border: none;
        outline: none;
        background-color: rgba(0, 0, 0, 0);
      }
    }

    .search-right {
      display: flex;
      align-items: center;
      position: absolute;
      right: 0;
      top: 0;
      bottom: 0;

      .submit-box {
        width: 120px;
        background-color: #2d8cf0;
        height: 100%;
        border-top-right-radius: 6px;
        border-bottom-right-radius: 6px;
        transition: all .2s;

        &:hover {
          background-color: #297ed9;
        }

        button {
          background-color: rgba(0, 0, 0, 0);
          width: 100%;
          height: 100%;
          border: none;
          outline: none;
          color: white;
          font-size: 16px;
          cursor: pointer;
        }
      }

      .close-icon {
        display: block;
        margin-right: 10px;
        cursor: pointer;
      }
    }
  }
}
</style>
